# Copyright (c) 2021 Contributors to the Eclipse Foundation
# 
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
# 
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0
# 
# SPDX-License-Identifier: EPL-2.0
#
import os
import re
import datetime
import xml.etree.ElementTree as ET
import html
import pathlib
    
def writeHTMLFile(logger, outbasedir, msgid, msgtext, explanationtext, operatorresponsetext):
    outpath = os.path.join(outbasedir, msgid+'.html')
    try:
       timestr = datetime.datetime.now().strftime("%H:%M:%S on %d %B %Y")

       outfile = open(outpath, "w", encoding="utf8")
       outfile.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n')
       outfile.write('<html dir="ltr">\n')
       outfile.write('<head>\n')
       outfile.write('<META http-equiv="Content-Type" content="text/html; charset=UTF-8">\n')

       outfile.write("<!-- HTML output file generated by nut_translation.py\n")
       outfile.write("     Generated at "+timestr+" -->\n\n")
   
       outfile.write('    <!--\n')
       outfile.write('**********************************************************************\n')
       outfile.write('* Copyright Contributor to Eclipse Foundation 2003-2021\n\n')
       outfile.write('* This program and the accompanying materials are made available under the\n')
       outfile.write('* terms of the Eclipse Public License 2.0 which is available at')
       outfile.write('* http://www.eclipse.org/legal/epl-2.0')
       outfile.write('**********************************************************************\n')
       outfile.write(' -->\n')
       outfile.write("   <title>"+msgid+"</title>\n")
       outfile.write("</head>\n")
       outfile.write("<body>\n")
       outfile.write("<p>\n")
       outfile.write("<b>"+msgid+": "+msgtext+"</b>\n")
       outfile.write("</p>\n")
       
       #I'm tempted to only print this section if the explanation isn't blank - that would be a change
       outfile.write("<p>\n<b>Explanation: </b>"+explanationtext+"</p>\n")
        
       #I'm tempted to only print this section if it isn't blank - that would be a change
       outfile.write("<p>\n<b>Operator Response: </b>"+operatorresponsetext+"</p>\n")

       outfile.write("</body>\n")
       outfile.write("</html>\n")
       outfile.close()

    except Exception as e:
       logger.error("Failed to write HTML file: %s - error %s" %
                         (outpath,  e))
       raise e 

def msgTextNodeToHTMLString(xmlnode):
    '''The node can contain innertext and tags like <q />'''
    strwithtags = ET.tostring(xmlnode).decode()
    
    #Remove starting tag
    str1  = re.sub("^<[^>]*>\n?",'',strwithtags)
    #Remove ending tag
    str2  = re.sub("<\s*/[^>]*>\s*\n?\s*$",'',str1)
    
    str3  = str2.lstrip()

    #Replace <q />'s with "
    str4      = re.sub("<\s*q[\s/]*>",'"',str3)
    ##Replace <br /> with <br> tags
    str5      = re.sub("<\s*br[\s]*/?\s*>",'<br>',str4)
    #<Remove <p/> tags
    str6  = re.sub("<\s*p\s*/\s*>",'\n',str5)
    
    if re.match("\s*<\s*p\s*>",str6):
        #Remove first <p> tag
        str7  = re.sub("<\s*p\s*>",'',str6,1)
        #Remove first </p> tag
        str8  = re.sub("<\s*/p\s*>\n?",'',str7,1)
    else:
        str8 = str6
     
    #If there is a blank line at the end... remove it
    str11 = re.sub("\n\n$","\n",str8)

    return str11

def mkHTMLPath(outbasedir):
    pathlib.Path(outbasedir).mkdir(parents=True, exist_ok=True)

def outputHTML(logger, inputfile, inputxmlroot, outbasedir):
    timestr = datetime.datetime.now().strftime("%H:%M:%S on %d %B %Y")
    logger.info("Converting "+inputfile+" to HTML output files in: "+outbasedir+" at "+timestr)
    
    mkHTMLPath(outbasedir)
    
    try:

       for child in inputxmlroot:
           if child.tag == "Message":
               msgnode = child
               msgid = None
               msgtext = None
               explanationtext = None
               operatorresponsetext = None

               if msgnode.attrib['ID']:
                   msgid = msgnode.attrib['ID']

               for mchild in msgnode:
                   if mchild.tag == "MsgText":
                       msgtextnode = mchild
                       msgtext = msgTextNodeToHTMLString(msgtextnode)
                   elif mchild.tag == "Explanation":
                       explanationtext = msgTextNodeToHTMLString(mchild)
                   elif mchild.tag == "OperatorResponse":
                       operatorresponsetext =  msgTextNodeToHTMLString(mchild)
               
               if msgtext and msgid:
                   writeHTMLFile(logger, outbasedir, msgid, msgtext, explanationtext, operatorresponsetext)
               else:
                   logger.error("Malformed message")
                   if msgid:
                       logger.error("Maformed message ID is "+msgid)
                   else:
                       logger.error("Maformed message ID is MISSING")
                   if msgtext:
                       logger.error("Maformed message text is "+msgtext)
                   else:
                       logger.error("Maformed message text is MISSING")

    except Exception as e:
       logger.error("Failed to parse data for HTML files - error %s" %
                         (e))
       raise e 
